﻿using Mes.Pendant.Common.DtoMapping;
using Mes.Pendant.SupplierReturn.IAppService;
using Mes.Pendant.SupplierReturnFiles;
using Mes.Pendant.Workstation.Dto;
using Mes.Pendant.Workstation.IAppService;
using Polly;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace Mes.Pendant.SupplierReturn
{
	public class SupplierReturn : ApplicationService, ISupplierReturnAppService
	{
		private readonly IRepository<SupplierReturnFiles.SupplierReturn, int> _supplierReturnRepository;

		public SupplierReturn(IRepository<SupplierReturnFiles.SupplierReturn, int> supplierReturnRepository)
		{
			_supplierReturnRepository = supplierReturnRepository;
		}

		public async Task<PagedResult> GetSupplierReturnList(int page, int limit, string? returnName, string? startDate, string? endDate)
		{
			var predicate = System.Linq.PredicateBuilder.New<SupplierReturnFiles.SupplierReturn>(true);
			if (!string.IsNullOrEmpty(returnName))
			{
				predicate = predicate.And(m => m.ReturnName.Contains(returnName));
			}
			if (!string.IsNullOrEmpty(startDate))
			{
				predicate = predicate.And(m => m.ReturnDate >= Convert.ToDateTime(startDate));
			}
			if (!string.IsNullOrEmpty(endDate))
			{
				predicate = predicate.And(m => m.ReturnDate <= Convert.ToDateTime(endDate));
			}
			var supplierReturnList = _supplierReturnRepository.GetListAsync(predicate).Result;


			PagedResult responseResult = new PagedResult();
			responseResult.CurrentPage = page;
			responseResult.PageSize = limit;
			responseResult.RowCount = supplierReturnList.Count();
			responseResult.PageCount = (int)Math.Ceiling((responseResult.RowCount) / (double)limit);
			responseResult.Queryable = supplierReturnList.OrderBy(p => p.Id).Skip((page - 1) * limit).Take(limit).AsQueryable();
			responseResult.Queryable = responseResult.Queryable.MapToList<SupplierReturnFiles.SupplierReturn>().AsQueryable();
			return responseResult;
		}
	}
}
